package com.iot08.api.service;

import com.iot08.common.entity.app.DeviceImsi;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/23 10:40
 */
@Slf4j
@Service
public class DeviceImsiService extends BaseService<DeviceImsi> {

    /**
     * @param imei
     * @param imsi
     * @param imsiDate
     * @time: 2021/1/23 11:08
     * @author: Rock
     * @version 1.0
     */
    public DeviceImsi checkUpdate(String imei, String imsi, Date imsiDate) {
        DeviceImsi deviceImsi = this.findById(imei);
        if (deviceImsi == null) {
            deviceImsi = new DeviceImsi();
            deviceImsi.setId(imei);
            deviceImsi.setUpdateTime(new Date());
            deviceImsi.setImsi(new HashMap<>());
            deviceImsi.getImsi().put(imsi, imsiDate);
            this.save(deviceImsi);
        } else {
            if (deviceImsi.getImsi() == null) {
                deviceImsi.setImsi(new HashMap<>());
            } else {
                //查询出来后Date类型会多8小时，所以需减去8小时再更新回去
                for (Map.Entry<String, Object> entry : deviceImsi.getImsi().entrySet()) {
                    if (entry.getValue() instanceof Date) {
                        DateUtil.hanldeMongoDate((Date) entry.getValue(), 2);
                    }
                }
            }
            deviceImsi.getImsi().put(imsi, imsiDate);
            Update update = new Update();
            update.set("imsi", deviceImsi.getImsi());
            update.set("warn", 1);
            update.set("updateTime", new Date());
            deviceImsi.setUpdateTime(new Date());
            deviceImsi.setWarn(1);
            this.updateById(imei, update);
        }
        return deviceImsi;
    }

}
